import {
  HYEventStore
} from "hy-event-store";

// API
import {
  APIPlayer
} from "../service/api_player"
// 歌词解析工具
import parseLyric from "../utils/parse-lyric.js"

// const audioContext = wx.createInnerAudioContext()
const audioContext = wx.getBackgroundAudioManager() // 使用前提 需在app.json里面配置 "requiredBackgroundModes":["audio"]

const playerStore = new HYEventStore({
  state: {
    id: 0,
    songInfo: {}, // 当前歌曲
    duartionTime: 0, // 歌曲总时长
    lyricInfos: [], // 歌曲歌词信息 
    currentTime: 0,
    currentIndex: 0,
    currentLyric: "",


    // currentSong: {},
    // durationTime: 0, // 总的时长
    // lyricInfos: [],  // 歌词数据,
    // currentTime: 0,   // 当前播放到的时间
    // currentLyricText: "",    // 当前显示的歌词
    // currentLyricIndex: 0,   // 当前歌词播放的索引



    playModeIndex: 0, // 播放模式 0:order 1:repeat 2: random
    isPlaying: false,

    playListSongs: [], // 播放列表
    playSongIndex: 0, // 播放的歌曲在列表中的索引

    isShowSongList: false, // 是否展示列表

    isStoping:false, // 歌曲是否 关闭

    isFirstPlay: true,
  },
  actions: {
    palyMusicWithSongIdAction(ctx, {
      id,
      isRefresh = false
    }) {
      if (ctx.id === parseInt(id) && !isRefresh) {
        this.dispatch("changeMusicPlayStatusAction", true);
        return
      }
      ctx.id = id
      // 0 修改播放的状态
      ctx.isPlaying = true
      ctx.songInfo = {};
      ctx.duartionTime = 0;
      ctx.lyricInfos = []
      ctx.currentTime = 0
      ctx.currentIndex = 0
      ctx.currentLyric = ""

      // 1 歌曲信息
      APIPlayer.getSongDetail(id).then(res => {
        ctx.songInfo = res.songs[0];
        ctx.duartionTime = res.songs[0].dt
        audioContext.title = res.songs[0].name;
      })
      // 2 歌词信息
      APIPlayer.getSongLyric(id).then(res => {
        const musicLyric = res.lrc.lyric;
        const lyricInfos = parseLyric(musicLyric)
        ctx.lyricInfos = lyricInfos
      })

      // 3 根据歌曲 id 使用 audioContext 播放歌曲
      audioContext.stop()
      audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
      audioContext.title = id // getBackgroundAudioManager 要求必须传这个属性
      audioContext.autoplay = true;

      this.dispatch("setupAudioContextListenerAction")
    },

    setupAudioContextListenerAction(ctx) {
      if (ctx.isFirstPlay) {
        // 1 监听歌曲可以播放时 播放歌曲
        audioContext.onCanplay(() => {
          audioContext.play()
        })

        // 2 监听歌曲在播放时 的当前时间
        audioContext.onTimeUpdate(() => {
          // 1 currentTime
          const currentTime = audioContext.currentTime * 1000;
          ctx.currentTime = currentTime

          // 2 currentIndex currentLyric
          const index = ctx.lyricInfos.findLastIndex(item => currentTime >= item.time);
          if (index >= 0 && index !== ctx.currentIndex) {
            const currentLyric = ctx.lyricInfos[index].text;
            ctx.currentIndex = index;
            ctx.currentLyric = currentLyric
          }
        })

        // 3 监听歌曲播放到结束的时候
        audioContext.onEnded(() => {
          this.dispatch("changeNewMusicAction", true)
        })

        // 4 监听音乐 暂停 
        audioContext.onPlay(() => {
          ctx.isPlaying = true
        })

        // 5 监听音乐 播放
        audioContext.onPause(() => {
          ctx.isPlaying = false
        })

        // 6 监听音乐 在后台 关闭播放；将音乐的播放状态 重置为 暂停状态；
        // 当你打开小程序 进来时；audioContext 对象相当于已经被销毁了 需要重新设置src title autoPaly等
        audioContext.onStop(() => {
          ctx.isPlaying = false;
          ctx.isStoping = true
        })

        ctx.isFirstPlay = false
      }
    },

    changeMusicPlayStatusAction(ctx, isPlaying = true) {
      ctx.isPlaying = isPlaying
      if(ctx.isPlaying && ctx.isStoping){
        audioContext.src = `https://music.163.com/song/media/outer/url?id=${ctx.id}.mp3`
        audioContext.title = ctx.songInfo.name // getBackgroundAudioManager 要求必须传这个属性
        audioContext.autoplay = true; 
        audioContext.startTime = ctx.currentTime / 1000
        ctx.isStoping = false
      }
      ctx.isPlaying ? audioContext.play() : audioContext.pause()
    },

    changeNewMusicAction(ctx, isNext = true) {
      let index = ctx.playSongIndex;

      switch (ctx.playModeIndex) {
        case 0:
          index = isNext ? index + 1 : index - 1
          if (index < 0) index = ctx.playListSongs.length - 1;
          if (index === ctx.playListSongs.length) index = 0
          break
        case 1:
          // 不做操作
          break
        case 2:
          index = Math.floor(Math.random() * ctx.playListSongs.length)
          break
      }

      const newSong = ctx.playListSongs[index];
      if (!newSong) {
        index = ctx.playSongIndex
      } else {
        ctx.playSongIndex = index
      }

      const id = newSong.id
      this.dispatch("palyMusicWithSongIdAction", {
        id,
        isRefresh: true
      })
    },

    deleteSongFromPlaySongListAction(ctx, {
      index
    }) {

      if (ctx.playListSongs.length === 1) {
        ctx.isShowSongList = false;
        audioContext.stop()
        wx.navigateBack()
        return;
      }

      if (index === ctx.playSongIndex) {
        const cloneSongs = JSON.parse(JSON.stringify(ctx.playListSongs));
        const nextIndex = index + 1 === ctx.playListSongs.length ? 0 : index + 1;

        const id = ctx.playListSongs[nextIndex].id;
        this.dispatch("palyMusicWithSongIdAction",{id});
        
        cloneSongs.splice(index, 1);
        ctx.playListSongs = cloneSongs;

        if(nextIndex === 0){
          ctx.playSongIndex = 0
        }

      }

      if (index < ctx.playSongIndex) {
        const cloneSongs = JSON.parse(JSON.stringify(ctx.playListSongs));
        cloneSongs.splice(index, 1);

        ctx.playListSongs = cloneSongs;
        ctx.playSongIndex--;
      }

      if (index > ctx.playSongIndex) {
        const cloneSongs = JSON.parse(JSON.stringify(ctx.playListSongs));
        cloneSongs.splice(index, 1);

        ctx.playListSongs = cloneSongs;
      }
    }
  }
})




export {
  audioContext,
  playerStore
}